/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.interceptors;

import com.cashmate.hibernate.pojo.Employees;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

/**
 *
 * @author dean
 */
public class GlobalInterceptor extends AbstractInterceptor {

    private static final Logger logger = Logger.getLogger(GlobalInterceptor.class);

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        try {
            final ActionContext context = ai.getInvocationContext();
            HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
            ServletContext sc = (ServletContext) context.get(StrutsStatics.SERVLET_CONTEXT);
//            HttpServletResponse response = (HttpServletResponse) context.get(StrutsStatics.HTTP_RESPONSE);
            HttpSession session = request.getSession();
            if (session == null) {
                logger.info("Anonymous access to server was denied.");
                Object action = ai.getAction();
                if (action instanceof ValidationAware) {
                    ((ValidationAware) action).addActionError("Unauthorized access. Please Login first");
                }
                return "nologin";
            } else {
                Employees e = (Employees) session.getAttribute("employee");
                Map<Employees, HttpSession> USERS = (HashMap<Employees, HttpSession>) sc.getAttribute("USERS");
                boolean isLoggedin = false;

                for (Employees emp : USERS.keySet()) {
                    if (emp.getIdnumber().equals(e.getIdnumber())) {
                        isLoggedin = true;
                        break;
                    }
                }
                if (!isLoggedin) {
                    logger.info("Anonymous access to server was denied.");
                    Object action = ai.getAction();
                    if (action instanceof ValidationAware) {
                        ((ValidationAware) action).addActionError("Unauthorized access. Please Login first");
                    }
                    return "nologin";
                } else {
                    String result = ai.invoke();
                    logger.debug("Passed Global Interceptor.");
                    return result;
                }
            }
        } catch (Exception e) {                                                                                             
            return "ERROR";
        }
    }
}
